import { Component, OnInit, ElementRef, ViewChild } from '@angular/core';
import {
  FormBuilder,
  Validators,
  FormGroup,
  AbstractControl,
  ValidationErrors,
} from '@angular/forms';
const checkboxOptions = [
  { label: '选项1', value: 'option1', checked: false },
  { label: '选项2', value: 'option2', checked: false },
  { label: '选项3', value: 'option3', checked: false },
];
@Component({
  selector: 'app-base-form',
  templateUrl: './base-form.component.html',
  styleUrls: ['./base-form.component.less'],
})
export class BaseFormComponent implements OnInit {
  // 表单添加tag
  @ViewChild('inputElement', { static: false }) inputElement?: ElementRef;
  validateForm!: FormGroup;
  controlStatusList = [
    { value: 0, label: '放行' },
    { value: 1, label: '阻断' },
  ];
  tags = [];
  inputVisible = false;

  inputErrTip = '此项是必填项！';

  constructor(private fb: FormBuilder) {}

  ngOnInit(): void {
    this.initForm();
  }

  // 初始化表单
  initForm() {
    this.validateForm = this.fb.group({
      rangePickerTime: [null],
      inputForm: [null, [Validators.required]],
      optionFrom: [''],

      // tags和tagInput都是标签表单
      tags: [],
      tagInput: [null, []],

      importance: [null, []],
      checkboxGroup: [
        [...checkboxOptions],
        [Validators.required, this.validateCheckboxGroup],
      ],
      // checkboxGroup: [''],
      inputNoLabel: [null],
    });
  }

  // 多选框至少选择一个规则校验
  validateCheckboxGroup(control: AbstractControl): ValidationErrors | null {
    const selectedOptions = control.value;
    let res = false;
    if (selectedOptions) {
      selectedOptions.map((item) => {
        res = res || item.checked;
      });
    }
    if (res) {
      return null; // 至少选择了一个选项，验证通过
    } else {
      return { required: true }; // 验证失败，没有选择任何选项
    }
  }

  // 重置表单
  resetForm(e: MouseEvent): void {
    e.preventDefault();
    this.validateForm.reset();
    this.tags = []; //重置标签
    for (const key in this.validateForm.controls) {
      if (this.validateForm.controls.hasOwnProperty(key)) {
        this.validateForm.controls[key].markAsPristine();
        this.validateForm.controls[key].updateValueAndValidity();
      }
    }
  }

  // 提交表单
  submitForm(): void {
    // 在提交前进行校验是否符合表单规则
    if (this.validateForm.valid) {
      console.log('submit', this.validateForm.value);
    } else {
      alert('必填项未填写！');
    }
  }

  // 失去焦点添加输入的内容进入tags标签数组
  handleInputConfirmTag(): void {
    let inputValue = this.validateForm.get('tagInput').value;
    if (inputValue && this.tags.indexOf(inputValue) === -1) {
      this.tags = [...this.tags, inputValue];
      this.updateTags();
    }
    this.validateForm.get('tagInput').setValue('');
    this.inputVisible = false;
  }

  // 显示tag输入框
  showInputTag(): void {
    this.inputVisible = true;
    setTimeout(() => {
      this.inputElement?.nativeElement.focus();
    }, 10);
  }

  // 点击删除icon移除tags
  handleCloseTag(removedTag: any): void {
    const res = [];
    this.tags.map((item) => {
      if (!item.includes(removedTag)) {
        res.push(item);
      }
    });
    this.tags = res;
    this.updateTags();
  }

  // 获取当前输入框的内容
  getInputValue() {
    let res = this.validateForm.get('inputForm').value;
    console.log('当前表单项输入框内容为：', res);
  }

  // 修改输入框内容
  changeInputValue() {
    let change = 'input';
    this.validateForm.get('inputForm').patchValue(change);
  }

  // 获取tags更新表单
  updateTags() {
    this.validateForm.get('tags').patchValue(this.tags);
  }

  // 显示所有tag
  showTags() {
    console.log('tags', this.tags);
  }

  // 禁用输入框
  disableInput() {
    this.validateForm.get('inputForm').disable();
  }

  // 解除禁用的输入框
  enableInput() {
    this.validateForm.get('inputForm').enable();
  }

  // 添加校验规则
  addRules() {
    this.validateForm
      .get('inputForm')
      .setValidators([Validators.required, Validators.minLength(5)]);
    this.inputErrTip = '此项是必填项！最少输入五个字符！';
    this.validateForm.get('inputForm').updateValueAndValidity();
  }

  // 移除单项校验规则
  removeRules() {
    this.validateForm.get('inputForm').clearValidators();
    this.inputErrTip = '';
    this.validateForm.get('inputForm').updateValueAndValidity();
  }


  // 重置表单项不会清除所有校验规则
  resetFormValue() {
    this.validateForm.reset();
    this.validateForm.get('checkboxGroup').setValue([
      { label: '选项1', value: 'option1', checked: false },
      { label: '选项2', value: 'option2', checked: false },
      { label: '选项3', value: 'option3', checked: false },
    ]);
  }

  // 清除表单所有校验规则
  clearFormRules() {
    Object.keys(this.validateForm.controls).forEach((key) => {
      const control = this.validateForm.get(key);
      // 清除控件的校验规则
      control.clearValidators();
      // 更新控件的校验状态
      control.updateValueAndValidity();
    });
  }

  // 获取表单值
  logFormValue() {
    console.log('表单值', this.validateForm.value);
  }
  // 获取禁用表单项值
  getDisableFormValue() {
    console.log('表单值', this.validateForm.getRawValue());
  }
  // 获取某一个表单项值的校验是否符合规则
  checkVerification(item) {
    console.log('查看validateForm的inputForm表单项的校验是否符合：', this.validateForm.get(item).valid);
    console.log('查看validateForm的inputForm表单项的校验是否不符合：', this.validateForm.get(item).invalid);
  }
}

